package com.xg.mina;

import com.xg.mina.message.Constant;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class ConnectEncoder extends ProtocolEncoderAdapter {
    @Override
    public void encode(IoSession ioSession, Object o, ProtocolEncoderOutput protocolEncoderOutput) throws Exception {
        if (o instanceof ConnectCommand) {
            ConnectCommand command = (ConnectCommand) o;
            //IoBuffer buffer = command.calc(ioSession);
            IoBuffer buffer = Constant.CONNECT;
            buffer.flip();

            int limit = buffer.limit();
            byte[] bytes = new byte[limit];
            System.arraycopy(buffer.array(), 0, bytes, 0, bytes.length);
            command.setBytes(bytes);
            protocolEncoderOutput.write(buffer);
        } else {
            protocolEncoderOutput.write(o);
        }
    }
}
